<?php

namespace App\Http\Controllers\V1\Admin;

use App\Models\V1\Admins;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\YourDataImport;

// 自定义的导入类
use Illuminate\Support\Facades\DB;

use Illuminate\Http\Request;

class ExcelController extends BaseController
{

    public function uploadUsers(Request $request)
    {
        $user_id = $request->input('user_id');
        $user_data = Admins::select('id', 'community_id')->find($user_id)->toArray();
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls,csv'
        ]);
        $file = $request->file('file');
        DB::beginTransaction();

        try {

            $import = new YourDataImport($user_data);
            Excel::import($import, $file);
            DB::commit();
            return response()->json(['message' => '导入成功']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => $e->getMessage(), 'error' => $e->getMessage()], 500);
        }
    }
}
